# -*- coding: utf-8 -*-
from flask import Flask, render_template, send_from_directory, request
import threading
import os
import datetime

def get_latest_log(file_path, line=5):
    """读取日志文件并返回最新的日志记录，时间格式转换为'N小时N分钟之前'"""
    try:
        # 构建日志文件的绝对路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        log_file = os.path.join(project_root, 'script_logs', f"{file_path.replace('.py', '_info.log')}")
        
        with open(log_file, 'r', encoding='utf-8') as f:
            logs = f.readlines()
        
        if logs:
            # 只保留最新的20条记录
            latest_logs = logs[-line:] if len(logs) >= line else logs
            processed_logs = []
            
            for log in latest_logs:
                # 提取时间戳部分（假设时间戳在行首）
                timestamp_str = log.split(' - ')[0]
                try:
                    # 解析时间戳
                    timestamp = datetime.datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S,%f")
                    # 计算时间差
                    time_diff = datetime.datetime.now() - timestamp
                    
                    # 转换为小时和分钟
                    hours = time_diff.seconds // 3600
                    minutes = (time_diff.seconds % 3600) // 60
                    
                    # 格式化时间差描述
                    if hours>0:
                        time_ago = f"{hours}时{minutes}分前"
                    else:
                        time_ago = f"{minutes}分钟前"

                    # 替换原日志中的时间戳为时间差描述
                    new_log = log.replace(timestamp_str, time_ago, 1)
                    processed_logs.append(new_log.strip())
                except ValueError:
                    # 如果时间戳格式不匹配，保留原日志
                    processed_logs.append(log.strip())
            
            return processed_logs, 0
        else:
            return ["没有日志记录"], 0
    except FileNotFoundError:
        return ["日志文件不存在"], 0

def start_web_app(manager):
    app = Flask(__name__)
 
    @app.route('/')
    def script_list():
        script_info = []
        for path, info in manager.scripts.items():
                    # 获取最新的日志记录
            latest_log,log_size = get_latest_log(info['name'],5)
            script_info.append({
                'name': info['name'],
                'path': path, # .replace('\\','/')
                'interval': info['interval'],
                'status': info['status'],
                "title":info['title'],
                "latest_log":latest_log,
                "log_size":log_size,
            })
            print(latest_log)
        return render_template('scripts.html', scripts=script_info)
    
    @app.route('/logs/<script_name>')
    def script_logs(script_name):
        for path, info in manager.scripts.items():
            if info['name'] == script_name:
                try:
                    logs,log_size = get_latest_log(script_name,30)
                    return render_template('logs.html', logs=logs, script_name=script_name)
                except FileNotFoundError:
                    return f"没有找到脚本的日志文件 {script_name}", 404
        return f"脚本 {script_name} 不存在", 404
    
    @app.route('/clear_script')
    def clear_script():
        script_path = request.args.get('script_path')
        try:
                # 获取项目根目录路径
            project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            # 构建日志文件的绝对路径
            now = datetime.datetime.now()
            log_file = os.path.join(project_root, 'script_logs', f"{script_path.replace('.py', '_info.log')}")
            with open(log_file, 'w', encoding='utf-8') as f:
                f.write(f"{now}  日志已清理\n\n")
            return f"脚本日志 {os.path.basename(script_path)} 清理成功"
        except FileNotFoundError:
            return f"脚本日志 {os.path.basename(script_path)} 清理失败"



    @app.route('/start_script')
    def start_script():
        script_path = request.args.get('script_path')
        full_path = os.path.join('scripts', script_path.lstrip('/'))

        if manager.start_script(full_path):
            return f"脚本 {os.path.basename(script_path)} 启动成功"
        return f"启动脚本失败 {os.path.basename(script_path)}"
 
    @app.route('/stop_script')
    def stop_script():
        script_path =  request.args.get('script_path')
        full_path = os.path.join('scripts', script_path.lstrip('/'))
        if manager.stop_script( f"{full_path}" ):
            return f"脚本 {os.path.basename(script_path)} 停止成功"
        return f"停止脚本失败 {os.path.basename(script_path)}"
 
    def run_web():
        app.run(host='0.0.0.0', port=manager.web_port)
    
    web_thread = threading.Thread(target=run_web)
    web_thread.daemon = True
    web_thread.start()
    manager.logger.info(f"Web服务器在端口上启动 {manager.web_port}")